<script setup lang="ts">
import { Form } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { PropType, reactive, watch, ref, defineEmits } from 'vue'
import { FormSchema } from '@/types/form'
import { IPData } from "@/api/auth/ip/types";
import { ElInput, ElButton } from "element-plus";


const props = defineProps({
  currentRow: {
    type: Object as PropType<Nullable<IPData>>,
    default: () => null
  },
  formSchema: {
    type: Array as PropType<FormSchema[]>,
    default: () => []
  }
})

const ipRange = ref({
  startIp: "",
  endIp: ""
});

const rules = reactive({
})

const { register, methods, elFormRef } = useForm({
  schema: props.formSchema
})

watch(
  () => props.currentRow,
  (currentRow) => {
    if (!currentRow) return
    const { setValues } = methods
    setValues(currentRow)
  },
  {
    deep: true,
    immediate: true
  }
)

const emit = defineEmits(['ipRangeParse'])

const ipRangeParse = () => {
  if (ipRange.value.startIp && ipRange.value.endIp) {
    const startIpArr = ipRange.value.startIp.split(".");
    const endIpArr = ipRange.value.endIp.split(".");
    if (startIpArr.length === 4 && endIpArr.length === 4) {
      const startNumber = Number(startIpArr[3]);
      const endNumber = Number(endIpArr[3]);
      if (endNumber > startNumber) {
        let ipList: String = "";
        for(let i = startNumber; i< endNumber; i++) {
          ipList += `,${startIpArr[0]}.${startIpArr[1]}.${startIpArr[2]}.${i}`
        }
        emit("ipRangeParse", ipList.substring(1));
      }
    }
  }
}

defineExpose({
  elFormRef,
  getFormData: methods.getFormData
})
</script>

<template>
  <Form :rules="rules" @register="register">
    <template #ipRange>
      <div class="flex">
        <ElInput v-model="ipRange.startIp" size="small"/>
        <span class="mx-2">-</span>
        <ElInput v-model="ipRange.endIp" size="small"/>
        <ElButton @click="ipRangeParse" class="ml-4">转换</ElButton>
      </div>
    </template>
  </Form>
</template>
